package com.hzit.filter;


import cn.hutool.core.util.StrUtil;
import com.hzit.properties.SecurityGatewayProperties;
import com.hzit.utils.JwtUtils;
import com.hzit.utils.ResponseUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 作者：李嘉浩
 * 时间：2024-08-24-9:29
 * 功能：
 */
@Configuration
@Slf4j
public class HzitGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    private SecurityGatewayProperties properties;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();          //获取请求对象
        ServerHttpResponse response = exchange.getResponse();       //获取相应对象
        ServerHttpRequest.Builder mutate = request.mutate();       //得到请求对象

        String path = request.getURI().getPath();
        //判断是否是白名单请求
        if (properties.getWhites().contains(path)) {
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst("Authorization");
        if (!StrUtil.isNotBlank(authorization)) {
            log.error("未登录，无法访问");
            return ResponseUtil.webFluxResponseWriter(response,"登录失败！");
        }
        String token = authorization.replace("Bearer ", "");
        Claims claims = JwtUtils.parseToken(token);
        Object uuid = claims.get("uuid");
        String key =getKey(uuid);
        Boolean s = stringRedisTemplate.hasKey(key);
        if (!s){
            log.error("未登录，解析错误无法访问");
            return ResponseUtil.webFluxResponseWriter(response,"登录失败！");
        }
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private String getKey(Object uuid) {
        return "access_token"+uuid;
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
